<template>
  <view class="orders">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <text class="back" @click="goBack">＜</text>
      <text class="nav-title">我的订单</text>
      <image class="nav-logo" src="/static/logo.png" mode="aspectFit" />
    </view>

    <!-- 标签页 -->
    <view class="tabs">
      <view v-for="(tab, idx) in tabs" :key="tab" :class="['tab', currentTab === idx ? 'active' : '']" @click="switchTab(idx)">{{ tab }}</view>
    </view>

    <!-- 订单列表 -->
    <scroll-view
      class="order-list"
      scroll-y="true"
      :style="{ height: scrollHeight + 'px' }"
      @scrolltolower="loadMore"
      :lower-threshold="100"
    >
      <view class="order-card" v-for="(item, idx) in filteredOrders" :key="item.id || idx" @click="goOrderDetail(item)">
        <view class="order-header">
          <text class="order-no">订单号：{{ item.orderNo }}</text>
          <text class="order-date">{{ item.createTime }}</text>
        </view>
        <view class="order-body">
          <view class="order-row">
            <text class="label">辅导项目：</text>
            <view class="type-btn">{{ getTutoringItemText(item.tutoringItem) }}</view>
            <view class="spacer"></view>
            <text class="label">预算区间：</text>
            <text class="budget">{{ formatBudget(item.budgetMin, item.budgetMax) }}</text>
          </view>
          <view class="order-row avatars-row">
            <view class="order-status">
              <text class="status-text">报名人数：</text>
              <text class="status-value">{{ item.deliverCount || 0 }}</text>
            </view>
            <view class="spacer"></view>
            <!-- 显示报名人头像 -->
            <view v-if="item.avatarList && item.avatarList.length > 0" class="avatars">
              <image v-for="(avatar, index) in item.avatarList.slice(0, 4)" :key="index"
                     class="avatar-small" :src="avatar || '/static/logo.png'" mode="aspectFill" />
              <text v-if="item.avatarList.length > 4" class="more-count">+{{ item.avatarList.length - 4 }}</text>
            </view>
            <!-- 查看报名按钮 -->
            <view class="signup-btn" @click.stop="viewSignups(item)">查看报名</view>
          </view>
        </view>
      </view>

      <!-- 加载更多状态 -->
      <view v-if="loadingMore" class="loading-state">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 没有更多数据 -->
      <view v-if="!pagination.hasMore && filteredOrders.length > 0" class="no-more-state">
        <text class="no-more-text">没有更多订单了</text>
      </view>

      <!-- 空状态 -->
      <view v-if="!loading && filteredOrders.length === 0" class="empty-state">
        <text class="empty-text">暂无{{ tabs[currentTab] }}订单</text>
      </view>
    </scroll-view>


  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useOrderStore } from '../../../store/order.js'
import { orderApi, constants } from '../../../api'
import { handleApiResponse, formatOrderData, handlePaginationData } from '../../../utils/apiHelper'

const orderStore = useOrderStore()

const tabs = ['待接单', '交付中', '待评价', '已评价']
const currentTab = ref(0)
const scrollHeight = ref(600)
const loading = ref(false)
const loadingMore = ref(false)
const orderList = ref([])
const pagination = ref({
  current: 1,
  size: 10,
  total: 0,
  hasMore: true
})

// 标签页对应的订单状态值
const tabStatusMap = {
  0: constants.STUDENT_ORDER_STATUS.WAITING_ACCEPT,    // 待接单
  1: constants.STUDENT_ORDER_STATUS.IN_DELIVERY,       // 交付中
  2: constants.STUDENT_ORDER_STATUS.WAITING_EVALUATE,  // 待评价
  3: constants.STUDENT_ORDER_STATUS.COMPLETED          // 已完成
}

// 计算属性，按tab筛选订单
const filteredOrders = computed(() => {
  return orderList.value
})

const goBack = () => {
  uni.navigateBack()
}

const goOrderDetail = (order) => {
  // 设置当前订单到store
  orderStore.setCurrentOrder(order)

  // 根据订单状态跳转到不同的详情页面
  let detailPageUrl = ''
  switch (order.status) {
    case 0: // 待接单
      detailPageUrl = './PendingOrderDetail'
      break
    case 1: // 交付中
      detailPageUrl = './InProgressOrderDetail'
      break
    case 2: // 待评价
      detailPageUrl = './WaitingEvaluationOrderDetail'
      break
    case 3: // 已评价
      detailPageUrl = './CompletedOrderDetail'
      break
    default:
      detailPageUrl = './PendingOrderDetail'
  }

  uni.navigateTo({
    url: detailPageUrl + '?orderId=' + order.id
  })
}

const viewSignups = (order) => {
  uni.navigateTo({
    url: './SignupList?orderId=' + order.orderNo
  })
}

// 加载订单列表
const loadOrderList = async (isRefresh = false) => {
  if (loading.value && isRefresh) return
  if (loadingMore.value && !isRefresh) return

  if (isRefresh) {
    loading.value = true
  } else {
    loadingMore.value = true
  }

  const orderStatus = tabStatusMap[currentTab.value]

  const params = {
    current: isRefresh ? 1 : pagination.value.current,
    size: pagination.value.size,
    orderStatus: orderStatus
  }

  const result = await handleApiResponse(
    orderApi.getStudentOrderList(params),
    {
      showLoading: false,
      showError: true
    }
  )

  loading.value = false
  loadingMore.value = false

  if (result.success) {
    const paginationData = handlePaginationData(
      { result: result.data },
      orderList.value,
      isRefresh
    )

    // 格式化订单数据
    orderList.value = paginationData.list.map(order => formatOrderData(order))
    pagination.value = paginationData.pagination
  }
}

// 加载更多数据
const loadMore = async () => {
  if (!pagination.value.hasMore || loadingMore.value) return

  pagination.value.current += 1
  await loadOrderList(false)
}

// 切换标签页
const switchTab = (index) => {
  if (currentTab.value === index) return

  currentTab.value = index
  pagination.value.current = 1
  orderList.value = []
  loadOrderList(true)
}

// 获取辅导项目文本
const getTutoringItemText = (item) => {
  return constants.TUTORING_ITEM_TEXT[item] || '未知'
}

// 格式化预算区间
const formatBudget = (min, max) => {
  return `${min}-${max}元`
}



onMounted(() => {
  // 计算滚动区域高度
  const systemInfo = uni.getSystemInfoSync()
  scrollHeight.value = systemInfo.windowHeight - 240 // 减去导航栏、标签页和tabbar高度

  // 加载初始数据
  loadOrderList(true)
})
</script>

<style scoped>
.orders {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 32rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
}

.back {
  font-size: 40rpx;
  color: #333;
  padding: 0 16rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
  text-align: center;
}

.nav-logo {
  width: 48rpx;
  height: 48rpx;
}

/* 标签页 */
.tabs {
  display: flex;
  background: #fff;
  border-bottom: 1rpx solid #eee;
}

.tab {
  flex: 1;
  text-align: center;
  padding: 24rpx 0 16rpx 0;
  color: #888;
  border-bottom: 4rpx solid transparent;
  font-size: 28rpx;
}

.tab.active {
  color: #1e98d7;
  border-bottom: 4rpx solid #1e98d7;
  font-weight: bold;
}

/* 订单列表 */
.order-list {
  flex: 1;
  padding: 0 24rpx;
}

.order-card {
  background: #fff;
  border-radius: 12rpx;
  margin-top: 24rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #333;
  color: #fff;
  padding: 20rpx 24rpx;
  font-size: 26rpx;
}

.order-no {
  font-weight: bold;
}

.order-date {
  font-size: 24rpx;
  opacity: 0.8;
}

.order-body {
  padding: 24rpx;
}

.order-row {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.order-row:last-child {
  margin-bottom: 0;
}

.label {
  color: #888;
  font-size: 26rpx;
  margin-right: 8rpx;
}

.type-btn {
  background: #1e98d7;
  color: #fff;
  border-radius: 8rpx;
  padding: 6rpx 24rpx;
  font-size: 26rpx;
  margin-right: 24rpx;
}

.budget {
  color: #333;
  font-size: 26rpx;
  margin-left: 8rpx;
  font-weight: 500;
}

.avatars-row {
  justify-content: space-between;
}

.avatars {
  display: flex;
}

.avatar {
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  border: 2rpx solid #fff;
  margin-right: -12rpx;
  background: #eee;
}

.signup-btn {
  background: #ff5a7a;
  color: #fff;
  border-radius: 8rpx;
  font-size: 26rpx;
  padding: 8rpx 24rpx;
  margin-left: auto;
}

.spacer {
  flex: 1;
}

/* 订单状态 */
.order-status {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.status-text {
  font-size: 24rpx;
  color: #666;
}

.status-value {
  font-size: 24rpx;
  color: #4caf50;
  font-weight: 500;
}

/* 评分显示 */
.rating-display {
  background: #fff3e0;
  color: #ff9800;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: bold;
  border: 1rpx solid #ffcc80;
}

.rating-score {
  font-size: 24rpx;
}

/* 头像列表 */
.avatars {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.avatar-small {
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  border: 2rpx solid #fff;
  box-shadow: 0 2rpx 4rpx rgba(0,0,0,0.1);
}

.more-count {
  font-size: 20rpx;
  color: #666;
  margin-left: 8rpx;
}

/* 加载状态 */
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

/* 没有更多数据状态 */
.no-more-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx;
}

.no-more-text {
  font-size: 28rpx;
  color: #ccc;
}

/* 空状态 */
.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
}


</style>